package e2e;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

public class TextSearch {

    public static void searchAndWrite(File directory, List<String> transactionIds, File outputFile) {
        Map<String, List<String>> resultMap = new HashMap<>();
        if (directory.isDirectory()) {
            searchInDirectory(directory, transactionIds, resultMap);
            writeResult(outputFile, resultMap);
        }
    }

    private static void searchInDirectory(File directory, List<String> transactionIds, Map<String, List<String>> resultMap) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    searchInDirectory(file, transactionIds, resultMap);
                } else if (file.isFile() && (file.getName().endsWith(".js") || file.getName().endsWith(".html"))) {
                    try {
                        searchInFile(file, transactionIds, resultMap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private static void searchInFile(File file, List<String> transactionIds, Map<String, List<String>> resultMap) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                for (String transactionId : transactionIds) {
                    if (line.contains(transactionId)) {
                        resultMap.computeIfAbsent(file.getAbsolutePath(), k -> new ArrayList<>()).add(transactionId);
                        break;
                    }
                }
            }
        }
    }

    private static void writeResult(File outputFile, Map<String, List<String>> resultMap) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            for (Map.Entry<String, List<String>> entry : resultMap.entrySet()) {
                writer.write("File: " + entry.getKey());
                writer.newLine();
                writer.write("Transaction IDs: ");
                for (String transactionId : entry.getValue()) {
                    writer.write(transactionId + " ");
                }
                writer.newLine();
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

